package com.sayai.work.tools.overtimes;

import com.deepoove.poi.XWPFTemplate;
import com.sayai.work.tools.overtimes.dao.RecordDao;
import com.sayai.work.tools.overtimes.data.OtRecordsEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class WorkerServices {

    private final RecordDao r;

    @Autowired
    public WorkerServices(RecordDao r) {
        this.r = r;
    }

    public void makeOvertime() throws IOException {

        List<OtRecordsEntity> gets = r.findIdateItype();
        List<WorkerData> workers = new ArrayList<>();
        for (OtRecordsEntity o : gets ) {
            List<OtRecordsEntity> once = r.findByIdateAndItype(o.getIdate(),o.getItype());
            String users = "";
            String contents = "";
            for (OtRecordsEntity one:once              ) {
                users = users + "," + one.getIusername() ;
                contents = contents + "," +  one.getIcontent() ;
            }
            users = users.replaceFirst(",","");
            contents = contents.replaceFirst(",","");
            workers.add(new WorkerData(users,contents,o.getIdate(),o.getItype()));
        }


        XWPFTemplate template = XWPFTemplate.compile("template.docx").render(new HashMap<String, Object>(){{
            put("workers",  workers);
        }});
        FileOutputStream out = new FileOutputStream("output.docx");
        template.write(out);
        out.flush();
        out.close();
        template.close();
    }
}
